<?php
use Nette\Application\UI;

final class MessagePresenter extends BasePresenter
{
    public function startup() 
    {
	if(!$this->getUser()->isLoggedIn()) {
	    if ($this->getUser()->getLogoutReason() === \Nette\Http\User::INACTIVITY) {
		$this->flashMessage('Boli ste odhlásený z dôvodu dlhej nečinnosti.');
	    }
	    $this->flashMessage('Najprv sa prihláste.');
	    $this->redirect('Sign:In');
	}
	
	parent::startup();
    }
    
    protected function createComponentVp()
    {
	return new VisualPaginator;
    }  
    
    public function renderInbox()
    {
	$vp = $this['vp'];
	
	$row = $this->model->getMsgs()->where(array('rcpt' => $this->getUser()->getId()))->order('timestamp DESC');
	
	$paginator = $vp->paginator;
	$paginator->itemsPerPage = 5;
	$paginator->itemCount = $row->count();

	$this->template->msgs = $row->limit($paginator->getLength(), $paginator->getOffset());
    }
    
    public function renderOutbox()
    {	
	$vp = $this['vp'];
	
	$row = $this->model->getMsgs()->where(array('from' => $this->getUser()->getId()))->order('timestamp DESC');
	
	$paginator = $vp->paginator;
	$paginator->itemsPerPage = 5;
	$paginator->itemCount = $row->count();

	$this->template->msgs = $row->limit($paginator->getLength(), $paginator->getOffset());	
    }   
    
    public function renderSingle($id = 0)
    {
	if($this->isPremium()) {
	    $row = $this->model->getMsgs()->find($id)->fetch();
	    $this->template->msg = $row;
	    if($row->read == 0 AND $row->rcpt == $this->getUser()->getId()) {
		$this->model->database->exec('UPDATE msgs SET `read` = 1 WHERE id = '.$id.'');
	    }
	} else {
	    $this->flashMessage('Najprv si aktivujte ucet');
	    $this->redirect('Message:Inbox');
	}
    }
    
    public function renderSend()
    {

    }

        /**
     * Message form component factory.
     * @return Nette\Application\UI\Form
     */
    protected function createComponentMessageForm()
    {
	    $form = new UI\Form;
	    
	    $form->addText('rcpt', 'Komu:')
		    ->setRequired('Vyplnte prijemcu !')
		    ->setDefaultValue($this->getParam('rcpt'));
	    
	    $form->addTextArea('msg', 'Sprava:')
		    ->setRequired('Vyplnte spravu');

	    $form->addSubmit('send', 'Poslat');

	    $form->addProtection('Vyprsala platnost, zadajte este raz');

	    $form->onSuccess[] = callback($this, 'messageFormSubmitted');
	    return $form;
    }



    public function MessageFormSubmitted($form)
    {
	    try {
		    $values = $form->getValues();	
		    // Existuje prijemca?
		    $row = $this->model->getUsers()->where(array('username' => $values->rcpt))->fetch();
		    if(!$row) {
			throw new RuntimeException('Taky uzivatel neexistuje.');
		    }
		    if($row->username == $this->getUser()->getIdentity()->username) {
			throw new RuntimeException('Sebe posielat spravu? :D Forever alone level 92');
		    }
		    $this->model->database->exec('INSERT INTO msgs', array(
			'from' => $this->getUser()->getId(),
			'rcpt' => $row->id,
			'content' => $values->msg,
			'timestamp' => new Nette\DateTime(),
			'read' => '0'
		    ));
			
		    $this->flashMessage('Sprava uspesna poslana');
		    $this->redirect('Message:Outbox');

	    } catch (RuntimeException $e) {
		    $form->addError($e->getMessage());
	    }
    }
}
